package socket.BIO_NIO_AIO.aio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable {
    private int port;
    private CountDownLatch latch;
    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port) {
        this.port = port;
        try {
            // 创建服务端通道
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            // 将服务端通道绑定到制定端口
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("服务启动，开始监听端口：" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doAccept() {
        asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
    }

    public CountDownLatch getLatch() {
        return latch;
    }
}
